package com.tsfyun.scm.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tsfyun.common.base.config.OrikaBeanMapper;
import com.tsfyun.common.base.constant.CacheConstant;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.common.base.util.TsfPreconditions;
import com.tsfyun.scm.system.entity.CustomsElements;
import com.tsfyun.scm.system.mapper.CustomsElementsMapper;
import com.tsfyun.scm.system.service.ICustomsElementsService;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.scm.system.util.TsfWeekendSqls;
import com.tsfyun.scm.system.vo.CustomsElementsVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 *  服务实现类
 * </p>
 *

 * @since 2020-03-19
 */
@Slf4j
@Service
public class CustomsElementsServiceImpl extends ServiceImpl<CustomsElements> implements ICustomsElementsService {

    @Autowired
    private CustomsElementsMapper customsElementsMapper;

    @Autowired
    private OrikaBeanMapper beanMapper;

    @Cacheable(value = CacheConstant.CUSTOMS_ELEMENTS_HS_CODE,key = "#hsCode")
    @Override
    public List<CustomsElementsVO> findByHsCode(String hsCode) {
        if(StringUtils.isEmpty(hsCode)) { return Lists.newArrayList(); }
        CustomsElements customsElements = new CustomsElements();
        customsElements.setHsCode(hsCode);
        List<CustomsElements> customsElementsList = super.list(customsElements);
        if(CollUtil.isNotEmpty(customsElementsList)) {
            customsElementsList =  customsElementsList.stream().
                    sorted(Comparator.comparing(CustomsElements::getSort))
                    .collect(Collectors.toList());
            return beanMapper.mapAsList(customsElementsList,CustomsElementsVO.class);
        }
        return Lists.newArrayList();
    }

    @CacheEvict(beforeInvocation = true,allEntries = true,value = CacheConstant.CUSTOMS_ELEMENTS_HS_CODE)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteAndSaveElementsByHsCode(String oldHsCode,String nowHsCode, List<String> elementsName, List<String> isNeeds) {
        customsElementsMapper.deleteByCustomsCode(oldHsCode);
        //判断是否有重复的要素名称
        elementsName.stream().forEach(StringUtils::removeSpecialSymbol);
        TsfPreconditions.checkArgument(elementsName.stream().filter(r->StringUtils.isEmpty(r)).count() < 1,new ServiceException("存在要素名称为空"));
        TsfPreconditions.checkArgument(elementsName.size() == elementsName.stream().distinct().count(),new ServiceException("要素名称重复"));
        IntStream.range(0,elementsName.size()).forEach(idx->{
            CustomsElements customsElements = new CustomsElements();
            customsElements.setId(StringUtils.UUID());
            customsElements.setHsCode(nowHsCode);
            customsElements.setName(StringUtils.removeSpecialSymbol(elementsName.get(idx)));
            customsElements.setSort(idx + 1);
            customsElements.setIsNeed("true".equals(isNeeds.get(idx)));
            customsElementsMapper.insert(customsElements);
        });
    }

    @Override
    public List<Map<String, String>> findByName(String name) {
        List<Map<String,String>> dataList = Lists.newArrayList();
        Example example = Example.builder(CustomsElements.class).where(TsfWeekendSqls.<CustomsElements>custom()
                .orLike(true,CustomsElements::getName,StringUtils.removeSpecialSymbol(name))).select("name").distinct().build();
        example.setOrderByClause("name asc");
        List<CustomsElements> customsElements = customsElementsMapper.selectByExampleAndRowBounds(example,new RowBounds(0,10));
        if(CollUtil.isNotEmpty(customsElements)) {
            customsElements.stream().forEach(customsElements1->{
                Map<String,String> map = Maps.newHashMap();
                map.put("name",customsElements1.getName());
                dataList.add(map);
            });
        }
        return dataList;
    }

    @CacheEvict(beforeInvocation = true,allEntries = true,value = CacheConstant.CUSTOMS_ELEMENTS_HS_CODE)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByCustomsCode(String hsCode) {
        customsElementsMapper.deleteByCustomsCode(hsCode);
    }

    @CacheEvict(beforeInvocation = true,allEntries = true,value = CacheConstant.CUSTOMS_ELEMENTS_HS_CODE)
    @Override
    public void clear() {
        log.info("清除要素缓存成功");
    }
}
